/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dahg.project.istu.web.menu;

import com.dahg.project.istu.controller.bean.menu.IMenuService;
import com.dahg.project.istu.controller.model.Menu;
import com.dahg.project.istu.controller.model.Rol;
import java.util.List;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.MenuModel;

/**
 *
 * @author dahg
 */
public class MenuFactory {
    
    private Rol rol;
    private IMenuService service;
    
    public MenuModel getModel(Rol rol, IMenuService service) {
        MenuModel model = new DefaultMenuModel();        
        List<Menu> rootMenu = service.getRootMenu(rol);
        
        if(rootMenu==null || rootMenu.isEmpty()) return model;
        
        this.rol = rol;
        this.service = service;        
        
        for(Menu menu: rootMenu) {
            if(isSubMenu(menu)) {
                SubMenu subMenu = new SubMenu(menu);
                addItemsToSubMenu(subMenu);
                model.addElement(subMenu);
            }
            else {
                MenuItem item = new MenuItem(menu);
                model.addElement(item);
            }
        }
        
        return model;
    }
    
    private void addItemsToSubMenu(SubMenu subMenu) {
        List<Menu> childs = service.getMenuChilds(subMenu.getMenu(), rol);
        
        if(!childs.isEmpty()) {
            for(Menu child:childs) {
                if(isSubMenu(child)) {
                    SubMenu subMenuChild = new SubMenu(child);
                    subMenu.addElement(subMenuChild);
                    addItemsToSubMenu(subMenuChild);
                }
                else
                    subMenu.addElement(new MenuItem(child));
            }
        }
    }
    
    private boolean isSubMenu(Menu menu) {
        return (menu.getTarget()==null || menu.getTarget().isEmpty());
    }
}
